package com.power.service.handler;

import com.power.service.util.ServiceTools;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class MyInvocationHandler implements InvocationHandler {

    //目标对象
    private Object target; //SomeServiceImp类

    public MyInvocationHandler(Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("invoke");
        System.out.println("methodName:"+method.getName());
        String methodName = method.getName();
        //通过代理对象执行方法时，会调用执行这个invoke（）
        Object res = null;
        //执行目标类的方法，通过Method类实现
        if("doSome".equals(methodName)) {
            ServiceTools.doLog();
            res = method.invoke(target, args); //SomeServiceImpl.doOther() doSome()
            ServiceTools.doTrans();
        } else {
            res = method.invoke(target, args); //SomeServiceImpl.doOther() doSome()
        }

        return res;
    }
}
